package sk.tramtatiri.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.RecipeDao;
import sk.tramtatiri.data.dataobjects.Recipe;

public class RecipeDaoJPAImp extends AbstractDaoJPAImpl<Recipe> implements RecipeDao{

	public RecipeDaoJPAImp() {
		super(Recipe.class);
	}

	@Transactional
	public List<Recipe> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<Recipe>>() {
			public List<Recipe> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Recipe> query = em.createQuery("select r from Recipe r order by r.name asc", Recipe.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Transactional
	public Recipe findName(final String name) {
		try{
			return getJpaTemplate().execute(new JpaCallback<Recipe>() {
				public Recipe doInJpa(EntityManager em) throws PersistenceException {
					TypedQuery<Recipe> query = em.createQuery("select r from Recipe r where name='"+name+"'", Recipe.class);
					return query.getSingleResult();
				}
			});
		}catch (Exception e) {
			return null;
		}
	}

	@Transactional
	public List<Recipe> orderBy(final String column) {
		return getJpaTemplate().execute(new JpaCallback<List<Recipe>>() {
			public List<Recipe> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Recipe> query = em.createQuery("select r from Recipe r order by " + column, Recipe.class);
				return query.getResultList();
			}
		});
	}
	
	@Transactional
	public List<String> findAllNames() {
		return getJpaTemplate().execute(new JpaCallback<List<String>>() {
			public List<String> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<String> query = em.createQuery("select r.name from Recipe r", String.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public void delete(Recipe o) {
		Recipe r = getJpaTemplate().find(Recipe.class, o.getId());
		getJpaTemplate().remove(r);
	}

}
